import { createRouter, createWebHashHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'

const modules: Record<string, any> = import.meta.glob(
  ['./modules/**/*.ts', '!./modules/**/remaining.ts'],
  { eager: true }
)

const routes: RouteRecordRaw[] = []
Object.keys(modules).forEach(key => routes.push(modules[key].default))

export const constantRoutes = () => {
  return routes
}

const router = createRouter({
  routes,
  history: createWebHashHistory()
})

// 路由拦截
router.beforeEach((to: { path: string }, from, next) => {
  const accessToken = localStorage.getItem('TOKEN')
  if (to.path !== '/login' && !accessToken) {
    next('/login')
  }
  next()
})

/**
 * 重置路由
 */
export function resetRouter() {
  router.replace({ path: '/login' })
}

export default router
